package com.yitao.cms.service.activity;

import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.skipper.base.bean.DataOutput;
import com.skipper.base.bean.PagedInput;
import com.skipper.base.bean.PagedOutput;
import com.skipper.base.data.querydsl.PredicateBuilder;
import com.skipper.base.service.GenericEntityService;
import com.skipper.base.utils.DateUtil;
import com.yitao.client.constant.ActivityEnums;
import com.yitao.client.dto.product.ProductGroupActivityDto;
import com.yitao.client.dto.shopInfo.ShopInfoDto;
import com.yitao.client.model.product.ProductGroupActivityModel;
import com.yitao.client.model.product.ProductInfoModel;
import com.yitao.client.model.product.QProductGroupActivityModel;
import com.yitao.cms.constant.UserErrorEnum;
import com.yitao.cms.constant.UserSession;
import com.yitao.cms.model.operationUser.OperationUserCmsModel;
import com.yitao.cms.service.product.ProductCmsService;
import com.yitao.cms.service.shopInfo.CmsShopInfoService;
import com.yitao.cms.utils.BaseUtils;
import com.yitao.cms.utils.DateUtils;
import com.yitao.cms.vo.activity.CmsProductGroupActivityDetailVo;
import com.yitao.cms.vo.activity.ProductGroupActivityInfoVo;
import com.yitao.cms.vo.activity.ProductGroupActivityVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

import static com.google.common.collect.Lists.newArrayList;
import static com.skipper.base.utils.DateUtil.DATE_TIME_PATTERN;

@Service
public class CmsProductGroupActivityService extends GenericEntityService<ProductGroupActivityModel, ProductGroupActivityDto, QProductGroupActivityModel> {

    private BaseUtils base = BaseUtils.getInstance();

    @Autowired
    private ProductCmsService productCmsService;

    @Autowired
    private CmsShopInfoService cmsShopInfoService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private CmsProductGroupActivityDetailService cmsProductGroupActivityDetailService;

    public CmsProductGroupActivityService(EntityManager entityManager) {
        super(entityManager);
    }

    //查询列表
    public PagedOutput<ProductGroupActivityVo> getProductGroupActivityList(PagedInput pagedInput, String productName, String productCode, String startTime, String endTime, Integer activityStates) {
        ProductGroupActivityDto productGroupActivityDto = new ProductGroupActivityDto();

        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            throw new RuntimeException("未登录");
        }
        Date startDate = null;
        if (StringUtils.isNotBlank(startTime)) {
            startDate = DateUtil.parseDate(startTime + " 00:00:00", DATE_TIME_PATTERN);
        }
        Date endDate = null;
        if (StringUtils.isNotBlank(endTime)) {
            endDate = DateUtil.parseDate(endTime + " 23:59:59", DATE_TIME_PATTERN);
        }
        productGroupActivityDto.setStartTime(startDate);
        productGroupActivityDto.setEndTime(endDate);
        productGroupActivityDto.setShopId(userSession.getShopId());
        productGroupActivityDto.setActivityStates(activityStates);
        productGroupActivityDto.setProductCode(productCode);
        productGroupActivityDto.setProductName(productName);
        return getProductGroupActivityModelListByBean(pagedInput, productGroupActivityDto);
    }

    //查询详情
    public DataOutput getProductGroupActivityById(Long activityId) {
        ProductGroupActivityModel productGroupActivityModel = queryFactory.select(Q).from(Q).where(Q.id.eq(activityId)).fetchOne();
        ProductGroupActivityInfoVo productGroupActivityInfoVo = null;
        if (productGroupActivityModel != null) {
            productGroupActivityInfoVo = new ProductGroupActivityInfoVo();
            BeanUtils.copyProperties(productGroupActivityModel, productGroupActivityInfoVo);
            productGroupActivityInfoVo.setActivityStates(productGroupActivityModel.getActivityStates());
            if (productGroupActivityModel.getStartTime() != null) {
                productGroupActivityInfoVo.setStartTime(DateUtils.getDateSecondFormat(productGroupActivityModel.getStartTime()));
            }
            if (productGroupActivityModel.getEndTime() != null) {
                productGroupActivityInfoVo.setEndTime(DateUtils.getDateSecondFormat(productGroupActivityModel.getEndTime()));
            }
            if (productGroupActivityInfoVo.getActivityStates() != null) {
                ActivityEnums.ActivityStatesEnum anEnum = ActivityEnums.ActivityStatesEnum.getEnum(productGroupActivityInfoVo.getActivityStates());
                if (anEnum != null) {
                    productGroupActivityInfoVo.setActivityStatesStr(anEnum.getName());
                }
            }
            if (productGroupActivityInfoVo.getShopId() != null) {
                ShopInfoDto shopInfoDto = cmsShopInfoService.getShopInfoById(productGroupActivityInfoVo.getShopId());
                if (shopInfoDto != null) {
                    productGroupActivityInfoVo.setShopName(shopInfoDto.getShopName());
                }
            }
            productGroupActivityInfoVo.setCmsProductGroupActivityDetailVoList(cmsProductGroupActivityDetailService.getListByActivityId(productGroupActivityModel.getId()));
        }
        return base.getSuccessMsg(productGroupActivityInfoVo);
    }

    /**
     * 验证不能同一段时间发布两个一样的商品活动
     *
     * @param productGroupActivityModel
     * @return
     */
    private ProductGroupActivityModel validationActivities(ProductGroupActivityModel productGroupActivityModel) {
        ProductGroupActivityModel productGroupActivityModel1 = null;
        List<ProductGroupActivityModel> fetch = queryFactory.select(Q).from(Q).where(Q.id.notIn(productGroupActivityModel.getId()).and(Q.endTime.gt(productGroupActivityModel.getStartTime())).and(Q.productId.eq(productGroupActivityModel.getProductId()))).fetch();
        if (fetch != null && fetch.size() != 0) {
            productGroupActivityModel1 = fetch.get(0);
        }
        return productGroupActivityModel1;
    }

    //添加修改
    @Transactional
    public DataOutput addOrUpdateProductGroupActivity(HttpServletRequest request, ProductGroupActivityInfoVo productGroupActivityInfoVo) {
        ProductGroupActivityModel productGroupActivityModel = new ProductGroupActivityModel();
        Date date = new Date();
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getCode());
        }
        ProductInfoModel productInfoModel = productCmsService.getProductInfoById(productGroupActivityInfoVo.getProductId());
        if (productGroupActivityInfoVo != null && productGroupActivityInfoVo.getId() != null) {
            ProductGroupActivityModel selectProductGroupActivityModel = queryFactory.select(Q).from(Q).where(Q.id.eq(productGroupActivityInfoVo.getId())).fetchOne();
            if (selectProductGroupActivityModel.getActivityStates() != null && selectProductGroupActivityModel.getActivityStates().equals(ActivityEnums.ActivityStatesEnum.UNPUBLISHED.getCode())) {
                if (selectProductGroupActivityModel.getEndTime().getTime() > date.getTime()) {
                    return base.getErrorMsg("当前活动已经发布不能修改");
                }
            }
            BeanUtils.copyProperties(productGroupActivityInfoVo, productGroupActivityModel);
            if (StringUtils.isNotBlank(productGroupActivityInfoVo.getStartTime())) {
                System.out.print(productGroupActivityInfoVo.getStartTime());
                productGroupActivityModel.setStartTime(DateUtil.parseDate(productGroupActivityInfoVo.getStartTime(), DATE_TIME_PATTERN));
            }
            if (StringUtils.isNotBlank(productGroupActivityInfoVo.getEndTime())) {
                System.out.print(productGroupActivityInfoVo.getEndTime());
                productGroupActivityModel.setEndTime(DateUtil.parseDate(productGroupActivityInfoVo.getEndTime(), DATE_TIME_PATTERN));
            }
            productGroupActivityModel.setId(selectProductGroupActivityModel.getId());
            productGroupActivityModel.setLastUpdateTime(date);
            productGroupActivityModel.setLastUpdateBy(Long.valueOf(userSession.getId()));
            productGroupActivityModel.setCreateBy(selectProductGroupActivityModel.getCreateBy());
            productGroupActivityModel.setCreateTime(selectProductGroupActivityModel.getCreateTime());
            productGroupActivityModel.setIsDelete(selectProductGroupActivityModel.getIsDelete());
            productGroupActivityModel.setShopId(userSession.getShopId());
            productGroupActivityModel.setActivityStates(ActivityEnums.ActivityStatesEnum.RELEASE.getCode());
        } else {
            BeanUtils.copyProperties(productGroupActivityInfoVo, productGroupActivityModel);
            if (StringUtils.isNotBlank(productGroupActivityInfoVo.getStartTime())) {
                productGroupActivityModel.setStartTime(DateUtil.parseDate(productGroupActivityInfoVo.getStartTime(), DATE_TIME_PATTERN));
            }
            if (StringUtils.isNotBlank(productGroupActivityInfoVo.getEndTime())) {
                productGroupActivityModel.setEndTime(DateUtil.parseDate(productGroupActivityInfoVo.getEndTime(), DATE_TIME_PATTERN));
            }

            productGroupActivityModel.setActivityStates(ActivityEnums.ActivityStatesEnum.RELEASE.getCode());
            productGroupActivityModel.setShopId(userSession.getShopId());
            productGroupActivityModel.setCreateBy(Long.valueOf(userSession.getId()));
            productGroupActivityModel.setCreateTime(date);
            productGroupActivityModel.setIsDelete(false);
        }

        if (productInfoModel != null) {
            productGroupActivityModel.setProductCode(productInfoModel.getProductCode());
            productGroupActivityModel.setProductId(productInfoModel.getId());
            productGroupActivityModel.setProductName(productInfoModel.getProductName());
        } else {
            return base.getErrorMsg("找不到当前产品");
        }
        ProductGroupActivityModel save = repository.save(productGroupActivityModel);
        if (save != null) {
            if (productGroupActivityInfoVo.getCmsProductGroupActivityDetailVoList() != null && productGroupActivityInfoVo.getCmsProductGroupActivityDetailVoList().size() != 0) {
                cmsProductGroupActivityDetailService.deleteByActivityId(save.getId());
                List<CmsProductGroupActivityDetailVo> cmsProductGroupActivityDetailVoList = productGroupActivityInfoVo.getCmsProductGroupActivityDetailVoList();
                for (CmsProductGroupActivityDetailVo cmsProductGroupActivityDetailVo : cmsProductGroupActivityDetailVoList) {
                    cmsProductGroupActivityDetailVo.setActivityId(save.getId());
                    cmsProductGroupActivityDetailVo.setProductCode(save.getProductCode());
                    cmsProductGroupActivityDetailVo.setProductId(save.getProductId());
                    cmsProductGroupActivityDetailVo.setCreateBy(userSession.getId());
                    cmsProductGroupActivityDetailVo.setCreateTime(date);
                    if (cmsProductGroupActivityDetailVo.getProductSkuDtoList() != null && cmsProductGroupActivityDetailVo.getProductSkuDtoList().size() > 0) {
                        List<CmsProductGroupActivityDetailVo> cmsProductGroupActivityDetailVoList1 = cmsProductGroupActivityDetailVo.getProductSkuDtoList();
                        for (CmsProductGroupActivityDetailVo cmsProductGroupActivityDetailVo1 : cmsProductGroupActivityDetailVoList1) {
                            cmsProductGroupActivityDetailVo1.setActivityId(save.getId());
                            cmsProductGroupActivityDetailVo1.setProductCode(save.getProductCode());
                            cmsProductGroupActivityDetailVo1.setProductId(save.getProductId());
                            cmsProductGroupActivityDetailVo1.setCreateBy(userSession.getId());
                            cmsProductGroupActivityDetailVo1.setCreateTime(date);
                            cmsProductGroupActivityDetailService.addProductGroupActivityDetail(cmsProductGroupActivityDetailVo1);
                        }
                    }
                    cmsProductGroupActivityDetailService.addProductGroupActivityDetail(cmsProductGroupActivityDetailVo);
                }
            }
        }
        return base.getSuccessMsg();
    }

    //修改状态
    @Transactional
    public DataOutput updateProductGroupActivityActivityStates(Long activityId, Integer activityStates, HttpServletRequest request) {
        if (activityId == null) {
            return base.getErrorMsg();
        }


        Date date = new Date();
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getCode());
        }
        ProductGroupActivityModel productGroupActivityModel = queryFactory.select(Q).from(Q).where(Q.id.eq(activityId)).fetchOne();
        if (productGroupActivityModel != null) {
            ProductInfoModel productInfoModel = productCmsService.getProductInfoById(productGroupActivityModel.getProductId());
            if (productInfoModel == null) {
                return base.getErrorMsg("查询不到当前产品请确认数据");
            }
            if (!productInfoModel.getIsSale()) {
                return base.getErrorMsg("此商品未上架不能参与活动");
            }
            if (productInfoModel.getIsDelete()) {
                this.deleteProductGroupActivityActivityStatesByProductId(productInfoModel.getId());
                return base.getErrorMsg("当前商品已被删除，此活动消息即将被删除请更新页面信息");
            }
            if (activityStates.equals(ActivityEnums.ActivityStatesEnum.UNPUBLISHED.getCode())) {
                if (productGroupActivityModel.getStartTime() == null || productGroupActivityModel.getEndTime() == null) {
                    return base.getErrorMsg("活动时间不能未空");
                }
                ProductGroupActivityModel productGroupActivityModel1 = validationActivities(productGroupActivityModel);
                if (productGroupActivityModel1 != null) {
                    if (productGroupActivityModel1.getEndTime() == null || productGroupActivityModel1.getStartTime() == null) {
                        return base.getErrorMsg();
                    }
                    return base.getErrorMsg("当前产品在" + DateUtils.getDateSecondFormat(productGroupActivityModel1.getStartTime()) + " - " + DateUtils.getDateSecondFormat(productGroupActivityModel1.getEndTime()) + "已有");
                }
            }
            productGroupActivityModel.setActivityStates(activityStates);
            productGroupActivityModel.setLastUpdateBy(Long.valueOf(userSession.getId()));
            productGroupActivityModel.setLastUpdateTime(date);
        }
        repository.save(productGroupActivityModel);
        return base.getSuccessMsg();
    }

    //产品下架活动商品同步下架
    @Transactional
    public void updateProductGroupActivityActivityStatesByProductId(Long productId) {
        repository.updateByWhere(PredicateBuilder.conjunction().and(() -> Q.productId.eq(productId)).get(),
                it -> it.set(Q.activityStates, ActivityEnums.ActivityStatesEnum.RELEASE.getCode()));
    }

    //产品删除同步活动商品删除
    @Transactional
    public void deleteProductGroupActivityActivityStatesByProductId(Long productId) {
        repository.updateByWhere(PredicateBuilder.conjunction().and(() -> Q.productId.eq(productId)).get(),
                it -> it.set(Q.isDelete, true));
    }

    //删除活动
    @Transactional
    public DataOutput deleteProductGroupActivityById(Long activityId, HttpServletRequest request) {
        if (activityId == null) {
            return base.getErrorMsg();
        }
        Date date = new Date();
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) { // 未登录
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getCode());
        }
        ProductGroupActivityModel productGroupActivityModel = queryFactory.select(Q).from(Q).where(Q.id.eq(activityId)).fetchOne();
        if (productGroupActivityModel != null) {
            productGroupActivityModel.setIsDelete(Boolean.TRUE);
            productGroupActivityModel.setLastUpdateBy(Long.valueOf(userSession.getId()));
            productGroupActivityModel.setLastUpdateTime(date);
        }
        repository.save(productGroupActivityModel);
        return base.getSuccessMsg();
    }

    private PagedOutput<ProductGroupActivityVo> getProductGroupActivityModelListByBean(PagedInput pagedInput, ProductGroupActivityDto productGroupActivityDto) {
        PagedOutput<ProductGroupActivityModel> productGroupActivityModelPagedOutput = repository.pagingList(PredicateBuilder.conjunction().
                ifNotNullThenAnd(productGroupActivityDto.getShopId(), () -> Q.shopId.in(productGroupActivityDto.getShopId())).
                ifHasTextThenAnd(productGroupActivityDto.getProductCode(), () -> Q.productCode.contains(productGroupActivityDto.getProductCode())).
                ifHasTextThenAnd(productGroupActivityDto.getProductName(), () -> Q.productName.contains(productGroupActivityDto.getProductName())).
                ifNotNullThenAnd(productGroupActivityDto.getActivityStates(), () -> Q.activityStates.in(productGroupActivityDto.getActivityStates())).
                ifNotNullThenAnd(productGroupActivityDto.getStartTime(), () -> Q.startTime.gt(productGroupActivityDto.getStartTime())).
                ifNotNullThenAnd(productGroupActivityDto.getEndTime(), () -> Q.endTime.lt(productGroupActivityDto.getEndTime())).
                ifNotNullThenAnd(false, () -> Q.isDelete.eq(false)).
                get(), pagedInput, new OrderSpecifier<>(Order.DESC, Q.createTime));
        List<ProductGroupActivityVo> productGroupActivityVoList = newArrayList();
        if (productGroupActivityModelPagedOutput != null) {
            List<ProductGroupActivityModel> productGroupActivityModelList = productGroupActivityModelPagedOutput.getData();
            if (productGroupActivityModelList != null && productGroupActivityModelList.size() != 0) {
                ProductGroupActivityVo productGroupActivityVo = null;
                for (ProductGroupActivityModel productGroupActivityModel : productGroupActivityModelList) {
                    productGroupActivityVo = new ProductGroupActivityVo();
                    BeanUtils.copyProperties(productGroupActivityModel, productGroupActivityVo);
                    productGroupActivityVo.setActivityStates(productGroupActivityModel.getActivityStates());
                    if (productGroupActivityModel.getStartTime() != null) {
                        productGroupActivityVo.setStartTime(DateUtils.getDateSecondFormat(productGroupActivityModel.getStartTime()));
                    }
                    if (productGroupActivityModel.getEndTime() != null) {
                        productGroupActivityVo.setEndTime(DateUtils.getDateSecondFormat(productGroupActivityModel.getEndTime()));
                    }
                    if (productGroupActivityVo.getActivityStates() != null) {
                        ActivityEnums.ActivityStatesEnum anEnum = ActivityEnums.ActivityStatesEnum.getEnum(productGroupActivityVo.getActivityStates());
                        if (anEnum != null) {
                            productGroupActivityVo.setActivityStatesStr(anEnum.getName());
                        }
                    }
                    if (productGroupActivityVo.getShopId() != null) {
                        ShopInfoDto shopInfoDto = cmsShopInfoService.getShopInfoById(productGroupActivityVo.getShopId());
                        if (shopInfoDto != null) {
                            productGroupActivityVo.setShopName(shopInfoDto.getShopName());
                        }
                    }
                    productGroupActivityVoList.add(productGroupActivityVo);
                }
            }
        }
        return new PagedOutput<ProductGroupActivityVo>(pagedInput, productGroupActivityModelPagedOutput.getTotalElements(), productGroupActivityVoList);
    }


    /**
     * 定时修改活动结束的
     */

    @Transactional
    public void taskUpdate() {
        Date date = new Date();
        List<ProductGroupActivityModel> fetch = queryFactory.select(Q).from(Q).where(Q.endTime.lt(new Date()).and(Q.activityStates.notIn(ActivityEnums.ActivityStatesEnum.END.getCode()))).fetch();
        if (fetch != null && fetch.size() != 0) {
            for (ProductGroupActivityModel productGroupActivityModel : fetch) {
                if (productGroupActivityModel != null) {
                    if (productGroupActivityModel.getEndTime().getTime() > date.getTime()) {
                        continue;
                    }
                    productGroupActivityModel.setActivityStates(ActivityEnums.ActivityStatesEnum.END.getCode());
                }
            }
            repository.save(fetch);
        }
    }
}
